import os
import datetime
import pytest
import shutil
from  settings import *
from psa.log import logger

class Runner:

    def __init__(self):

        self.run_report_dir = os.path.join(PROJECT_DIR, 'report','last')
        if os.path.exists(os.path.join(self.run_report_dir,'allure')):
            shutil.rmtree(os.path.join(self.run_report_dir,'allure'))
        if os.path.exists(os.path.join(self.run_report_dir,'pytest')):
            shutil.rmtree(os.path.join(self.run_report_dir,'pytest'))
            

        self.allure_file_dir = os.path.join(REPORT_DIR, 'last', 'allure', 'file').replace(PROJECT_DIR,".")
        self.allure_report_dir = os.path.join(REPORT_DIR, 'last', 'allure', 'report').replace(PROJECT_DIR,".")
        self.pytest_html = os.path.join(REPORT_DIR, 'last', 'pytest','pytest.html').replace(PROJECT_DIR,".")



    def run(self, case_name):
        pytest.main([
            "--html={}".format(self.pytest_html),
            "--alluredir={}".format(self.allure_file_dir),
            "-s",
            "-v",
            case_name
        ])

    def create_allure_report(self):
        allure_str = "allure generate {} -o {} --clean".format(self.allure_file_dir, self.allure_report_dir)
        os.system(allure_str)

    def save_report_to_history(self):
        report_time = datetime.datetime.now().strftime('%Y%m%d_%H%M%S')
        report_dir = os.path.join(REPORT_DIR, "history", report_time)
        if os.path.exists(report_dir):
            os.makedirs(report_dir)
        shutil.copytree(self.run_report_dir, report_dir)

if __name__ == '__main__':
    run = Runner()
    # run_case = os.path.join(PROJECT_DIR,"testcases","test_001.py").replace(PROJECT_DIR,'.')
    run_case = os.path.join(PROJECT_DIR,"testcases","test_fixtrue_demo.py::TestPyTestFixtrue").replace(PROJECT_DIR,'.')
    logger.info("@@@@ run case: {}".format(run_case))
    run.run(run_case)
    run.create_allure_report()
    run.save_report_to_history()
